Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

correct auth for legacy overview #460

Merged
merged 3 commits into from
Nov 8, 2024
Merged

correct auth for legacy overview #460

merged 3 commits into from
Nov 8, 2024

Conversation

Andreass2
Copy link
Collaborator

@Andreass2 Andreass2 commented Nov 8, 2024

Description

Correct authentication for legacy based on logged in user.

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)
  • All tests run green

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

Summary by CodeRabbit

  • New Features

    • Enhanced user access validation for correspondence, now incorporating additional parameters for improved authentication levels.
    • Introduced legacy support in authorization requests to accommodate existing systems.
  • Bug Fixes

    • Improved error handling and logging for user access checks and correspondence retrieval.
  • Documentation

    • Updated method signatures to reflect changes in parameters and functionality for better clarity.
  • Refactor

    • Streamlined authorization logic and request handling processes for improved maintainability and clarity.

@Andreass2 Andreass2 marked this pull request as ready for review November 8, 2024 07:35
Copy link
Contributor

coderabbitai bot commented Nov 8, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces significant changes to the handling of user access and correspondence history retrieval within the LegacyGetCorrespondenceHistoryHandler and LegacyGetCorrespondenceOverviewHandler classes. Key modifications include updates to method parameters for access checks, adjustments in error handling, and enhancements in the construction of response objects. The IAltinnAuthorizationService interface and related classes have also been updated to reflect these changes, particularly in how authorization requests are structured and processed.

Changes

File Change Summary
src/Altinn.Correspondence.Application/GetCorrespondenceHistory/LegacyGetCorrespondenceHistoryHandler.cs Updated Process method to modify parameters for access checks and adjusted error handling and response construction.
src/Altinn.Correspondence.Application/GetCorrespondenceOverview/LegacyGetCorrespondenceOverviewHandler.cs Modified Process method to change parameters for access checks and refined error handling logic.
src/Altinn.Correspondence.Core/Repositories/IAltinnAuthorizationService.cs Changed method signature of CheckUserAccessAndGetMinimumAuthLevel to include new mandatory parameters.
src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationDevService.cs Updated method signature of CheckUserAccessAndGetMinimumAuthLevel to align with new parameter requirements.
src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationService.cs Refactored methods for user access checks, updated method signatures, and introduced new request handling methods.
src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnTokenXacmlMapper.cs Added new method for legacy decision requests and modified existing methods to accommodate new parameters.

Possibly related PRs

Suggested labels

kind/bug, kind/enhancement

Suggested reviewers

  • CelineTrammi
  • RagnarFatland-Avanade

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Andreass2 Andreass2 added kind/feature-request New feature or request ignore-for-release pull request wont be included in release notes labels Nov 8, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Outside diff range and nitpick comments (5)
src/Altinn.Correspondence.Core/Repositories/IAltinnAuthorizationService.cs (1)

8-8: Ensure secure handling of SSN.

The method now accepts SSN (Social Security Number) which is sensitive PII data. Ensure all implementations:

  1. Use secure transport (HTTPS)
  2. Implement proper logging practices (no SSN in logs)
  3. Follow data protection regulations
src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationDevService.cs (1)

20-20: Document the significance of auth level 3

Consider extracting the magic number 3 to a named constant and documenting its significance in the context of authentication levels.

+ private const int DefaultDevAuthLevel = 3; // Represents highest security level for development
- return Task.FromResult((int?)3);
+ return Task.FromResult((int?)DefaultDevAuthLevel);
src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationService.cs (3)

115-115: Update method documentation to reflect signature change

The AuthorizeRequest method now accepts a XacmlJsonRequestRoot parameter. Ensure that any documentation or XML comments for this method are updated to reflect this change for clarity.


149-157: Refactor to eliminate code duplication in decision request methods

The methods CreateDecisionRequest and CreateDecisionRequestForLegacy share similar logic regarding personIdClaim and issuer checks. Consider refactoring shared logic into a private helper method to reduce duplication and improve maintainability.

Apply this diff to refactor the shared logic:

+ private bool IsAltinnTokenIssuer(Claim? personIdClaim)
+ {
+     return personIdClaim is null || personIdClaim.Issuer == $"{_altinnOptions.PlatformGatewayUrl.TrimEnd('/')}/authentication/api/v1/openid/";
+ }

- if (personIdClaim is null || personIdClaim.Issuer == $"{_altinnOptions.PlatformGatewayUrl.TrimEnd('/')}/authentication/api/v1/openid/")
+ if (IsAltinnTokenIssuer(personIdClaim))
{
    // Existing logic
}

152-156: Consider more informative exception handling

In CreateDecisionRequestForLegacy, throwing a generic SecurityTokenInvalidIssuerException may not provide sufficient context. Consider throwing a more specific exception or including a descriptive message to aid in debugging.

Apply this diff to enhance exception handling:

- throw new SecurityTokenInvalidIssuerException();
+ throw new SecurityTokenInvalidIssuerException($"Unsupported issuer: {personIdClaim?.Issuer}");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between deeb1d9 and 7342998.

📒 Files selected for processing (6)
  • src/Altinn.Correspondence.Application/GetCorrespondenceHistory/LegacyGetCorrespondenceHistoryHandler.cs (1 hunks)
  • src/Altinn.Correspondence.Application/GetCorrespondenceOverview/LegacyGetCorrespondenceOverviewHandler.cs (1 hunks)
  • src/Altinn.Correspondence.Core/Repositories/IAltinnAuthorizationService.cs (1 hunks)
  • src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationDevService.cs (1 hunks)
  • src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationService.cs (3 hunks)
  • src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnTokenXacmlMapper..cs (4 hunks)
🧰 Additional context used
📓 Learnings (1)
src/Altinn.Correspondence.Application/GetCorrespondenceHistory/LegacyGetCorrespondenceHistoryHandler.cs (1)
Learnt from: CelineTrammi
PR: Altinn/altinn-correspondence#413
File: src/Altinn.Correspondence.Application/GetCorrespondenceHistory/LegacyGetCorrespondenceHistoryResponse.cs:17-21
Timestamp: 2024-10-29T13:10:17.164Z
Learning: The `PartyId` and `AuthenticationLevel` properties in the `LegacyUser` class (in `src/Altinn.Correspondence.Application/GetCorrespondenceHistory/LegacyGetCorrespondenceHistoryResponse.cs`) are still under development, and the correct validation has not been determined yet.
🔇 Additional comments (7)
src/Altinn.Correspondence.Core/Repositories/IAltinnAuthorizationService.cs (1)

8-8: LGTM! Verify implementation updates.

The signature change aligns well with the PR objective of correcting authentication for legacy overview. The addition of SSN parameter and non-nullable recipientOrgNo strengthens the authentication process.

Let's verify that all implementations have been updated:

✅ Verification successful

Interface implementation and usage verified successfully

The verification shows that:

  • The interface is properly implemented in both AltinnAuthorizationService and AltinnAuthorizationDevService
  • All calls to CheckUserAccessAndGetMinimumAuthLevel in handlers (LegacyGetCorrespondenceOverviewHandler and LegacyGetCorrespondenceHistoryHandler) use the correct signature with SSN and required recipientOrgNo parameters
  • The implementations and usages are consistent with the interface changes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for implementations of IAltinnAuthorizationService
# and verify they implement the new method signature correctly

# Find all implementations
ast-grep --pattern 'class $_ : $$$IAltinnAuthorizationService$$$'

# Find all calls to CheckUserAccessAndGetMinimumAuthLevel
rg -A 3 'CheckUserAccessAndGetMinimumAuthLevel'

Length of output: 3596

src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationDevService.cs (1)

18-21: Verify development service usage

This development service implementation always returns auth level 3 and grants all access. Please ensure this is only used in development/test environments.

Consider adding environment checks or throwing NotSupportedException if accidentally used in production.

✅ Verification successful

Based on the search results, I can now generate a final response:

Development service is properly isolated

The AltinnAuthorizationDevService is only used in development scenarios when maskinportenSettings.ClientId is empty, while production uses the real AltinnAuthorizationService. The service registration in DependencyInjection.cs shows proper environment-based switching:

  • Development: Uses AltinnAuthorizationDevService when no Maskinporten client ID is configured
  • Production: Uses real AltinnAuthorizationService with Maskinporten HTTP client registration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if this development service is referenced in production configurations
# Expected: No matches in production config files

# Search for references to AltinnAuthorizationDevService in config files
rg -l "AltinnAuthorizationDevService" | rg -i "prod|release|deployment"

Length of output: 71


Script:

#!/bin/bash
# Let's try a more comprehensive verification approach:

# 1. Find all references to this service class
echo "=== Direct references to AltinnAuthorizationDevService ==="
rg "AltinnAuthorizationDevService"

# 2. Check where IAltinnAuthorizationService is registered in DI
echo -e "\n=== DI registrations for IAltinnAuthorizationService ==="
rg "IAltinnAuthorizationService" -A 5 -B 5

# 3. Look for environment-specific configuration files
echo -e "\n=== Environment configurations ==="
fd -e json -e xml "appsettings|config" --exec grep -l "Authorization"

Length of output: 63213

src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnTokenXacmlMapper..cs (1)

Line range hint 37-159: Verify the security implications of the legacy authorization path.

The introduction of a new authorization path for legacy systems warrants careful security review:

  1. Verify that the legacy path is only used when absolutely necessary
  2. Ensure proper access controls are in place
  3. Check for potential security vulnerabilities

Run the following script to analyze the usage:

✅ Verification successful

Security review of legacy authorization path reveals controlled usage and proper safeguards

Based on the analysis of the codebase:

  1. The legacy authorization path (CreateAltinnDecisionRequestForLegacy) is only used within the AltinnAuthorizationService in a controlled manner, specifically for legacy correspondence operations.

  2. SSN handling follows secure practices:

    • No hardcoded sensitive data found
    • SSNs are properly mapped to URN identifiers (urn:altinn:person:identifier-no)
    • Access checks are consistently performed before operations involving SSNs
  3. Authorization checks are properly implemented:

    • Minimum auth level verification is required for all operations
    • Resource-based access control is enforced
    • Claims and scopes are validated before granting access
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze the usage of legacy authorization methods and potential security implications

# Test 1: Find all usages of the legacy decision request method
echo "=== Legacy Decision Request Usage ==="
rg -A 5 "CreateAltinnDecisionRequestForLegacy"

# Test 2: Check for potential hardcoded SSNs or sensitive data
echo -e "\n=== Potential Sensitive Data ==="
rg -i "ssn|socialsecurity|personnumber"

# Test 3: Analyze authorization service implementations
echo -e "\n=== Authorization Service Usage ==="
ast-grep --pattern 'class $_ : IAltinnAuthorizationService {
  $$$
  CheckUserAccessAndGetMinimumAuthLevel($$$) {
    $$$
  }
  $$$
}'

Length of output: 11531

src/Altinn.Correspondence.Application/GetCorrespondenceOverview/LegacyGetCorrespondenceOverviewHandler.cs (1)

49-49: Verify updated method calls across the codebase

The method CheckUserAccessAndGetMinimumAuthLevel now includes userParty.SSN as a parameter. Please ensure that all other invocations of this method throughout the codebase have been updated to include the new ssn parameter to prevent any potential runtime errors due to mismatched method signatures.

Run the following script to locate all usages of the method and verify their parameter lists:

✅ Verification successful

Based on the search results, I can generate the final response as we have comprehensive information about all usages of the CheckUserAccessAndGetMinimumAuthLevel method in the codebase:

All usages of CheckUserAccessAndGetMinimumAuthLevel are correctly implemented

All invocations of the method are consistent with the interface definition and include the required ssn parameter:

  • Interface definition in IAltinnAuthorizationService.cs specifies ssn as first parameter
  • Implementation in AltinnAuthorizationDevService.cs matches interface
  • Implementation in AltinnAuthorizationService.cs matches interface
  • Usage in LegacyGetCorrespondenceHistoryHandler.cs correctly passes recipientParty.SSN
  • Usage in LegacyGetCorrespondenceOverviewHandler.cs correctly passes userParty.SSN
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all calls to CheckUserAccessAndGetMinimumAuthLevel include the new 'ssn' parameter.

# Test: Search for all invocations of the method. Expect: All calls should include 'ssn' as the first argument.
rg 'CheckUserAccessAndGetMinimumAuthLevel' --type cs -C 2

Length of output: 4176

src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationService.cs (3)

50-51: Refactored code enhances readability and consistency

The extraction of actionIds and creation of jsonRequest using CreateDecisionRequest improves code clarity and aligns with the updated authorization flow.


64-64: Verify handling of null return value

Changing the return value to null when validation fails may impact calling methods that expect a different type. Verify that all consumers of CheckUserAccessAndGetMinimumAuthLevel correctly handle a null return to prevent possible NullReferenceExceptions or unexpected behavior.


151-151: ⚠️ Potential issue

Ensure personIdClaim is not null before accessing properties

In CreateDecisionRequestForLegacy, ensure that personIdClaim is not null before accessing its Issuer property to prevent a potential NullReferenceException.

Apply this diff to safely access personIdClaim:

- if (personIdClaim is null || personIdClaim.Issuer == /* condition */)
+ if (personIdClaim == null || personIdClaim.Issuer == /* condition */)
{
    // Existing logic
}

Likely invalid or redundant comment.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationService.cs (2)

60-68: Consider making the minimum authentication level configurable.

The method returns a hard-coded authentication level of 3 when validation succeeds. This might need to be configurable based on different security requirements or environments.

Consider:

  1. Moving this to configuration
  2. Making it dependent on the resource type or access level requested
  3. Adding documentation explaining why level 3 was chosen

Line range hint 115-133: LGTM! Consider enhancing error details in response.

The error handling is comprehensive, but we could improve the logging of failure responses.

Consider adding more detailed error logging:

 if (!response.IsSuccessStatusCode)
 {
+    var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
+    _logger.LogError("Authorization request failed. Status: {StatusCode}, Error: {Error}",
+        response.StatusCode, errorContent);
     return null;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7342998 and 2071925.

📒 Files selected for processing (1)
  • src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationService.cs (3 hunks)
🔇 Additional comments (2)
src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnAuthorizationService.cs (2)

Line range hint 60-157: Verify token validation and authentication flow.

The changes handle sensitive operations and multiple authentication methods. Let's verify the security implications:

#!/bin/bash
# Check for proper token validation across the codebase
echo "Checking token validation patterns..."
rg -A 5 "ValidateToken|ValidateAsync|SecurityToken" 

echo "Checking authentication middleware configuration..."
rg -A 10 "UseAuthentication|AddAuthentication"

echo "Checking for potential authentication bypasses..."
ast-grep --pattern 'if.*IsDevelopment.*return true'

50-52: LGTM! Verify CreateDecisionRequest usage across codebase.

The refactoring to use CreateDecisionRequest improves code organization. Let's verify its usage pattern across the codebase.

✅ Verification successful

Let me try a different search pattern to find the CreateDecisionRequest usage.


Based on the search results, I can now generate the final response:

CreateDecisionRequest usage is consistent and properly implemented

The method is used correctly in two scenarios:

  • Standard flow using CreateDecisionRequest(user, actionIds, resourceId, recipientOrgNo)
  • Legacy flow using CreateDecisionRequestForLegacy(user, ssn, actionTypes, resourceId, orgnr)

Both implementations properly handle token validation and map to the appropriate XACML request format through AltinnTokenXacmlMapper.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all calls to CreateDecisionRequest to ensure consistent usage
ast-grep --pattern 'CreateDecisionRequest($$$)'

Length of output: 17160


Script:

#!/bin/bash
# Search for CreateDecisionRequest method definition and its usages
ast-grep --pattern 'CreateDecisionRequest($$$)'
# Also search with ripgrep for better context
rg -A 5 'CreateDecisionRequest'

Length of output: 4152

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnTokenXacmlMapper..cs (1)

71-81: Consider refactoring to enhance code maintainability

The CreateResourceCategory method now includes additional parameters legacy and orgNr, introducing conditional logic based on the legacy flag. To improve readability and maintainability, consider separating the legacy and non-legacy logic into distinct methods or refactoring the method to reduce complexity.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2071925 and 58925f3.

📒 Files selected for processing (1)
  • src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnTokenXacmlMapper..cs (4 hunks)
🔇 Additional comments (2)
src/Altinn.Correspondence.Integrations/Altinn/Authorization/AltinnTokenXacmlMapper..cs (2)

37-57: Method implementation aligns with existing patterns

The CreateAltinnDecisionRequestForLegacy method correctly constructs the XacmlJsonRequestRoot for legacy scenarios, ensuring that the access subject, action, and resource categories are appropriately set. The logic is consistent with the existing CreateAltinnDecisionRequest method.


121-133: ⚠️ Potential issue

Validation of the ssn parameter is recommended

The CreateSubjectCategoryForLegacy method accepts an ssn parameter but does not validate its format. For security and data integrity, consider implementing validation to ensure the ssn conforms to the expected Norwegian SSN format.

Apply this diff to add SSN validation:

private static XacmlJsonCategory CreateSubjectCategoryForLegacy(ClaimsPrincipal user, string ssn)
{
+   if (!IsValidNorwegianSSN(ssn))
+   {
+       throw new ArgumentException("Invalid SSN format", nameof(ssn));
+   }

    XacmlJsonCategory xacmlJsonCategory = new XacmlJsonCategory();
    List<XacmlJsonAttribute> list = new List<XacmlJsonAttribute>();
    var claim = user.Claims.FirstOrDefault(claim => IsScopeClaim(claim.Type));
    if (claim is not null)
    {
        list.Add(CreateXacmlJsonAttribute("urn:altinn:person:identifier-no", ssn, "string", claim.Issuer));
        list.Add(CreateXacmlJsonAttribute("urn:scope", claim.Value, "string", claim.Issuer));
    }
    xacmlJsonCategory.Attribute = list;
    return xacmlJsonCategory;
}

+private static bool IsValidNorwegianSSN(string ssn)
+{
+    // Norwegian SSN validation logic
+    return Regex.IsMatch(ssn, @"^\d{11}$");
+}

Likely invalid or redundant comment.

Copy link
Collaborator

@CelineTrammi CelineTrammi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work! :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-for-release pull request wont be included in release notes kind/feature-request New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants